import { forEachFormOptions } from '@/utils/formMakeUtils.js';
import { getLeaderByUser } from '@/api/process';

/**
 * 计算用户关联
 * @param {*} changeElement 被修改的用户字段
 * @param {*} formOptions formOptions
 * @param {*} options subformIndex、userInfo、handleFormUserSelect、isInDetail、eventData
 */
export function userChange(changeElement, formOptions, options) {
  const userFollowerData = formOptions.config && formOptions.config.userFollowerData || {};
  let linkUserList = userFollowerData[changeElement.key];
  if (options.isInDetail && !changeElement.isSubTable) {
    linkUserList = linkUserList && linkUserList.filter(linkKey => {
      if (options.eventData && options.eventData[linkKey] && options.eventData[linkKey].isEventEdit) {
        return true;
      }
      return false;
    });
  }
  if (linkUserList && linkUserList.length) {
    // 人员选择映射处理
    forEachFormOptions(formOptions.list, (element, subformKey, parentSubform) => {
      if (linkUserList.includes(element.key)) {
        let value = changeElement.value;
        if (parentSubform && (options.subformIndex || options.subformIndex === 0)) {
          value = parentSubform.value[options.subformIndex][changeElement.key];
        }
        getLeaderByUserApi(element, value, options, parentSubform);
      }
    });
  }
}

function getLeaderByUserApi(element, value, options, parentSubform) {
  const type = element.options.defaultValue - 2;
  let ids = '';
  if (type < 3) {
    ids = `${options.userInfo.id}`;
  } else {
    if (value && Array.isArray(value)) {
      ids = value.map(i => i.id).join(',');
    } else if (value) {
      ids = value.id;
    }
  }
  if (!ids) {
    setValue(element, element.options.multiple ? [] : '', options, parentSubform);
    return [];
  }
  const params = {
    ids,
    type
  };
  getLeaderByUser(params).then(res => {
    if (res.code === 200) {
      const ans = element.options.multiple ? res.data || [] : res.data[0] || '';
      setValue(element, ans, options, parentSubform);
    }
  }).catch(err => {
    console.error(err.message);
  });
}

function setValue(element, value, options, parentSubform) {
  if (!element.isSubTable) {
    element.value = value;
    options.handleFormUserSelect(element, value);
  } else if (parentSubform) {
    if (parentSubform.value[options.subformIndex]) {
      parentSubform.value[options.subformIndex][element.key] = value;
    }
    options.handleFormUserSelect(element, value);
  }
}
